from fastapi import APIRouter, Depends, HTTPException
from typing import Optional
from pydantic import BaseModel
from module_admin.service.salary_service import SalaryService
from sqlalchemy.ext.asyncio import AsyncSession
from sql.database import get_db

salaryController = APIRouter(prefix="/system/salary", tags=["薪资管理"])

class SalaryQuery(BaseModel):
    pageNum: int = 1
    pageSize: int = 10
    name: Optional[str] = None
    month: Optional[int] = None

class SalaryCreate(BaseModel):
    employeeId: int
    month: int
    totalPayment: float = 0
    socialSecurity: float = 0

class SalaryUpdate(BaseModel):
    salaryId: int
    totalPayment: Optional[float] = None
    socialSecurity: Optional[float] = None

@salaryController.get("/list")
async def get_salary_list(query: SalaryQuery = Depends(), db: AsyncSession = Depends(get_db)):
    """获取薪资列表"""
    service = SalaryService(db)
    return await service.get_salary_list(query.dict())

@salaryController.get("/{salary_id}")
async def get_salary(salary_id: int, db: AsyncSession = Depends(get_db)):
    """获取薪资详情"""
    service = SalaryService(db)
    salary = await service.get_salary_by_id(salary_id)
    if not salary:
        raise HTTPException(status_code=404, detail="薪资记录不存在")
    return {"data": salary}

@salaryController.post("")
async def create_salary(salary: dict, db: AsyncSession = Depends(get_db)):
    """创建薪资记录"""
    service = SalaryService(db)
    try:
        return await service.create_salary(salary)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@salaryController.put("")
async def update_salary(salary: dict, db: AsyncSession = Depends(get_db)):
    """更新薪资记录"""
    service = SalaryService(db)
    try:
        return await service.update_salary(salary)
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))

@salaryController.delete("/{salary_id}")
async def delete_salary(salary_id: int, db: AsyncSession = Depends(get_db)):
    """删除薪资记录"""
    service = SalaryService(db)
    if await service.delete_salary(salary_id):
        return {"message": "删除成功"}
    raise HTTPException(status_code=404, detail="薪资记录不存在") 